// 时间转字符串 输出时间字符串 yyyy-mm-dd hh:MM
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(_formatNumber).join('/')} ${[hour, minute].map(_formatNumber).join(':')}`

  function _formatNumber(n) {
    n = n.toString()
    return n[1] ? n : `0${n}`
  }
}

/** 
 提示成功后延迟返回 
 title 成功提示语句
 backData 设置返回去上一页的值 与方法backData联用
 * */
const back = (title,backData=null) => {
  wx.showToast({
    title,
    icon: 'success',
    duration: 1500
  })
  if(backData){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2]; //上一个页面
    prevPage.setData({
      backData
    });
  }
  let timer = setTimeout(() => {
    clearTimeout(timer)
    wx.navigateBack({
      delta: 1
    })
  }, 1200)
}
/** 获取上一页返回的值  与back联用*/
const backData=()=>{
    const pages = getCurrentPages()
    const currPage = pages[pages.length - 1]
    return currPage.data.backData
}

// 过来时间字符串为时间如：'2022-12-12 12:12:12'=>'12:12:12'
const time = (value) => {
  if (!value) return ''
  const index = value.indexOf(' ')
  return value.substring(index + 1)
}

/**
 *  验证必填 验证失败提示后终止进程
 * values验证值
 * titles失败提示文字
 * */ 
const required=(values,titles)=>{
  for(let i=0;i<values.length;i++){
    if(!values[i]){
      let title=titles && titles[i] ||'请输入'
      wx.showToast({
        title,
        icon: 'error',
        duration: 1500
      })
      throw console.error(title);
    }
  }
}
module.exports = {
  formatTime,
  time,
  back,
  backData,
  required
}